package com.fw.application.security.comm;

import cn.hutool.json.JSONUtil;
import com.fw.constant.Constant;
import com.fw.enums.CodeStatus;
import com.fw.exception.CustomException;
import com.fw.mes.Result;

import com.fw.system.web.model.entity.TbUser;
import com.fw.system.web.service.ITbUserService;
import com.fw.utils.AuthUtils;
import com.fw.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private AuthUtils authUtils;

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private ITbUserService userService;

    /**
     * 内部过滤
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //得到header中权限信息
        //得到header中权限信息
        String authHeader = request.getHeader(Constant.RequestConstant.HEAD_FLAG);
        if (authHeader != null && authHeader.startsWith(Constant.RequestConstant.BEARER)) {
            String authToken = authHeader.substring(Constant.RequestConstant.BEARER.length());
            String userId = authUtils.parseJWT(authToken).getId();
            if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
/*
                ((BaseUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).get
*/
            }
        }
        filterChain.doFilter(request, response);

        }
}
